//
//  LoginViewController.m
//  APJ HRadar
//
//  Created by Richard Zhao on 3/5/14.
//  Copyright (c) 2014 APJ. All rights reserved.
//

#import "LoginViewController.h"
#import "Const.h"
#import "User.h"
#import "HRStore.h"
#import "Encrypt.h"
#import "syncDataService.h"
#import "NetworkConfigViewController.h"
#import "UIView+Toast.h"

@interface LoginViewController ()
{
    UIPopoverController *configPop;
}
@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"login_bg"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(doHideKeyBoard)];
    
    tap.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer: tap];
    [tap setCancelsTouchesInView:NO];
    
}

- (void)doHideKeyBoard{
    [userId resignFirstResponder];
    [password resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
    userId.text = [[NSUserDefaults standardUserDefaults] stringForKey:LAST_LOGIN_USER_KEY];
    //password.text=@"test01";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)login:(id)sender {
    NSString *uid = userId.text;
    NSString *pwd = password.text;
    BOOL loginSuccess = NO;
    
    User *u = [[HRStore sharedStore] findUserById:uid];
    
    if (u) {
        NSString *dbPWD = [u password];
        
        loginSuccess = [Encrypt isHashMatchedFrom:pwd to:dbPWD];
        loginSuccess = YES;  // TO-DO just for testing.
        if (loginSuccess) {
            extern BOOL hasLogin;
            hasLogin = YES;
            [[NSUserDefaults standardUserDefaults] setValue:uid forKey:LAST_LOGIN_USER_KEY];
            [[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.view makeToast:@"Password incorrect!"
                        duration:3.0
                        position:[NSValue valueWithCGPoint:CGPointMake(500, 700)]];
        }
    } else {
        [self.view makeToast:@"User not exists, please check user name or Refresh Account for update from server."
                    duration:4.0
                    position:[NSValue valueWithCGPoint:CGPointMake(523, 700)]];
    }
}

- (IBAction)networkSetup:(id)sender {
    CGRect rect = [[self view] convertRect:[sender bounds] fromView:sender];
    NetworkConfigViewController *netConfig = [[NetworkConfigViewController alloc] init];
    configPop = [[UIPopoverController alloc] initWithContentViewController:netConfig];
    [configPop setDelegate:self];
    [netConfig setPopView:configPop];
    [configPop setPopoverContentSize:CGSizeMake(460, 109)];
    [configPop presentPopoverFromRect:rect inView:[self view]
           permittedArrowDirections:UIPopoverArrowDirectionUp
                           animated:YES];
}

- (void) syncUserTable{
    
    [self->userId setEnabled:NO];
    [self->password setEnabled:NO];
    [self->loading startAnimating];
    [self->data setEnabled:NO];
    [self->login setEnabled:NO];
    [self->setting setEnabled:NO];
    
    // 异步线程，防止UI被卡
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL syncSuccess = YES;
        syncSuccess = [[syncDataService sharedService] updateUserTable];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self->userId setEnabled:YES];
            [self->password setEnabled:YES];
            [self->data setEnabled:YES];
            [self->login setEnabled:YES];
            [self->setting setEnabled:YES];
            [self->loading stopAnimating];
            if (syncSuccess) {
                [self.view makeToast:@"同步成功！"
                            duration:3.0
                            position:[NSValue valueWithCGPoint:CGPointMake(500, 700)]];
            } else {
                [self.view makeToast:@"同步失败！"
                            duration:3.0
                            position:[NSValue valueWithCGPoint:CGPointMake(500, 700)]];
            }
            
        });
    });
}

- (IBAction)refreshAccount:(id)sender {
    [self syncUserTable];
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    if (popoverController == configPop) {

    }
    
    [popoverController dismissPopoverAnimated:YES];
    popoverController = nil;
}
@end
